<?php

namespace app\components\validators;

use yii\validators\Validator;
use yii\db\ActiveRecordInterface;

class Exist extends Validator
{
    public $targetClass;

    public $targetAttribute;

    public function validateAttribute($model, $attribute)
    {
        if ($model->$attribute > 0 || $model->$attribute) {
            /* @var $targetClass ActiveRecordInterface */
            $targetClass = $this->targetClass;
            $exist = $targetClass::find()->where([$this->targetAttribute => $model->$attribute])->exists();
            if (!$exist)
                $this->addError($model, $attribute, 'no exist');
        }
    }
}